// GST计算测试脚本
const axios = require('axios');

// 测试数据
const testCases = [
  {
    name: "单个商品 - 咖啡 (S$18.80)",
    items: [{ menu_item_id: 1, quantity: 1, special_instructions: "" }]
  },
  {
    name: "两个商品 - 咖啡 + 薯条",
    items: [
      { menu_item_id: 1, quantity: 1, special_instructions: "" },
      { menu_item_id: 2, quantity: 1, special_instructions: "" }
    ]
  }
];

// 前端GST计算逻辑（从CartView.swift移植）
function calculateFrontendGST(cartTotal) {
  // 税前小计（从含税价格倒算）
  const subtotalBeforeGST = cartTotal / 1.09;
  
  // 假设没有折扣
  const discount = 0;
  const subtotalAfterDiscount = Math.max(0, subtotalBeforeGST - discount);
  
  // GST计算
  const tax = subtotalAfterDiscount * 0.09;
  
  // 总计
  const total = subtotalAfterDiscount + tax;
  
  return {
    subtotal: parseFloat(subtotalBeforeGST.toFixed(2)),
    discount: parseFloat(discount.toFixed(2)),
    subtotalAfterDiscount: parseFloat(subtotalAfterDiscount.toFixed(2)),
    tax: parseFloat(tax.toFixed(2)),
    total: parseFloat(total.toFixed(2))
  };
}

// 获取管理员token
const adminToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW4xQGV4YW1wbGUuY29tIiwibWVtYmVyc2hpcExldmVsIjoiYWRtaW4iLCJpYXQiOjE3NTYyNjk0NzIsImV4cCI6MTc1NjM1NTg3Mn0.Ej8Oj8Ej8Oj8Oj8Oj8Oj8Oj8Oj8Oj8Oj8Oj8Oj8Oj8";

async function testGSTCalculation() {
  console.log('=== GST计算对比测试 ===\n');
  
  for (const testCase of testCases) {
    console.log(`测试用例: ${testCase.name}`);
    console.log('=' .repeat(50));
    
    try {
      // 调用后端API创建订单
      const response = await axios.post('http://localhost:3001/api/orders', {
        items: testCase.items,
        order_type: 'dine_in',
        payment_method: 'cash',
        table_number: 1
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${adminToken}`
        }
      });
      
      const backendResult = response.data;
      console.log('后端响应数据:');
      console.log(JSON.stringify(backendResult, null, 2));
      
      console.log('\n后端计算结果:');
      console.log(`  小计: S$${backendResult.data.subtotal}`);
      console.log(`  税额: S$${backendResult.data.tax_amount}`);
      console.log(`  总计: S$${backendResult.data.total_amount}`);
      
      // 计算前端结果 - 使用商品原价作为购物车总价
      const itemPrice = backendResult.data.items[0].price; // 获取第一个商品的价格
      const frontendResult = calculateFrontendGST(itemPrice);
      
      console.log('\n前端计算结果:');
      console.log(`  小计: S$${frontendResult.subtotal}`);
      console.log(`  税额: S$${frontendResult.tax}`);
      console.log(`  总计: S$${frontendResult.total}`);
      
      // 比较结果
      console.log('\n差异分析:');
      const subtotalDiff = Math.abs(backendResult.data.subtotal - frontendResult.subtotal);
      const taxDiff = Math.abs(backendResult.data.tax_amount - frontendResult.tax);
      const totalDiff = Math.abs(backendResult.data.total_amount - frontendResult.total);
      
      console.log(`  小计差异: S$${subtotalDiff.toFixed(2)}`);
      console.log(`  税额差异: S$${taxDiff.toFixed(2)}`);
      console.log(`  总计差异: S$${totalDiff.toFixed(2)}`);
      
      if (subtotalDiff < 0.01 && taxDiff < 0.01 && totalDiff < 0.01) {
        console.log('  ✅ 计算结果一致');
      } else {
        console.log('  ❌ 计算结果不一致');
      }
      
    } catch (error) {
      console.error('测试失败:', error.response?.data || error.message);
    }
    
    console.log('\n');
  }
}

// 运行测试
testGSTCalculation().catch(console.error);